package com.wiloon.java8x.proxy;

/**
 * Created by wiloon on 7/30/14.
 */

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHelper {
	private static Logger logger = LoggerFactory.getLogger(HttpHelper.class);

	public static HttpEntity httpGetEntity(String url) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet httpGet = new HttpGet(url);
		HttpEntity entity = null;
		logger.debug("request line:" + httpGet.getRequestLine());
		try {

			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
			entity = httpResponse.getEntity();
			if (entity != null) {
				// logger.debug("contentEncoding:" +
				// entity.getContentEncoding());

			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return entity;
	}

	public static String httpGet(String url) throws ParseException, IOException {
		HttpEntity entity = httpGetEntity(url);
		return EntityUtils.toString(entity, "UTF-8");
	}

	public static String httpPost(String url, String payload) {
		logger.debug("http post:" + url);
		logger.debug("payload:" + payload);
		String rtn = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-type", "application/json; encoding=utf-8");

		try {

			if (!StringUtils.isBlank(payload))
				httpPost.setEntity(new StringEntity(payload, "UTF-8"));

			CloseableHttpResponse response = httpclient.execute(httpPost);

			HttpEntity entity = response.getEntity();

			rtn = EntityUtils.toString(entity, "UTF-8");

			EntityUtils.consume(entity);
			response.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.debug("response:" + rtn);
		return rtn;
	}

}
